using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;

namespace Cache
{
    public partial class frmCaches : Form
    {

        private const string ZoomInScript = "zoomIn";
        private const string ZoomOutScript = "zoomOut";
        private const string PanScript = "pan";
        private const string RemovePushpinScript = "removePushpin";
        private const string AddPushpinScript = "addPin";
        private const string SetMapStyleScript = "setMapStyle";
        private const string ResizeScript = "resize";
        private const string ClearPushpinsScript = "clearPushpins";
        private const string StartVE = "startVE";
        private const string SetCenterAndZoom = "setCenterAndZoom";
        private const string GetMap = "GetMap";
        private const string resizeMap = "resizeMap";
        private const string centerOrPan = "centerOrPan";
        
        MapPosition mapPos = new MapPosition();

        public Boolean FormLoad;
        
        private BindingSource bindingSource1 = new BindingSource();
        private SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter();        

        public frmCaches()
        {
            InitializeComponent();

        }

        private void frmCaches_Load(object sender, EventArgs e)
        {
            Options Options = new Options();

            //http://www.geocaching.com/seek/cache_details.aspx?wp=GCQ2ZF&Submit6=Go
            DataGridView.DataSource = bindingSource1;
            tslblFnd.BackColor = Color.FromArgb(Convert.ToInt32(Options.GetOption("CacheFoundColor")));
            tslblPLC.BackColor = Color.FromArgb(Convert.ToInt32(Options.GetOption("CachePlacedColor")));
            tslblARC.BackColor = Color.FromArgb(Convert.ToInt32(Options.GetOption("CacheArchivedColor")));

            
            DataGridViewCheckBoxColumn ckb = new DataGridViewCheckBoxColumn();
            chkArchived.Enabled = true;
            
            this.DataGridView.Columns.Insert(0, ckb);

            DataGridViewColumn column = DataGridView.Columns[0];
            column.Width = 20;

            chkArchived.Checked = Convert.ToBoolean(Options.GetOption("CacheDispArchived"));
            chkFound.Checked = Convert.ToBoolean(Options.GetOption("CacheDispFound"));
            chkPlaced.Checked = Convert.ToBoolean(Options.GetOption("CacheDispPlaced"));

            GetData("");

            //populate the stat boxes in the toolstrip.
            tslblFnd.Text = GetStats("FOUND").ToString();
            tslblARC.Text = GetStats("Archived").ToString();
            tslblDNF.Text = GetStats("NOTFOUND").ToString();
            tslblTTL.Text = GetStats("Total").ToString();
            tslblPLC.Text = GetStats("Placed").ToString();


            // Find the Location of VirtualEarth.html
            string BrowserURL = Application.ExecutablePath;
            BrowserURL = BrowserURL.Substring(0, BrowserURL.LastIndexOf("\\"));
            BrowserURL = Path.Combine(BrowserURL, @"VE\VirtualEarthMap.html");
            

            // Start the load of VirtualEarth.html into the WebBrowser.
            // When done, the callback below (DocumentedCompleted) gets called.
            virtualEarthMapBrowser.Url = new Uri(BrowserURL);
            virtualEarthMapBrowser.ObjectForScripting = this;

            FormLoad = false;
        }


        public void OverlayClicked(string ID)
        {
            MessageBox.Show("Clicked! \r\nString: " + ID.ToString());

        }
        private void virtualEarthMapBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // once the HTML page has finished loading, we start VE, passing current map
            // parameters.
            
            //executeScript(StartVE, virtualEarthMapBrowser.Width, virtualEarthMapBrowser.Height, mapPos.lat, mapPos.lon, mapPos.zoom);

            executeScript(GetMap);
            executeScript(resizeMap);
            //executeScript(ResizeScript, virtualEarthMapBrowser.Width, virtualEarthMapBrowser.Height);
        }

        // final initialization step: when the VE script executed above finishes loading.  Put any
        // stuff here that needs to be done after the map is initialized (e.g. adding new pushpins).
        public void scriptLoadCompleted()
        {
            Cursor.Current = Cursors.WaitCursor;
           
            //Add the caches to the map.
            PopulateMap();
            Options Options = new Options();

            
            string HomeLat = Options.GetHomeLocation(Options.GetOption("HomeLocation"), "Lat");
            string HomeLon = Options.GetHomeLocation(Options.GetOption("HomeLocation"), "Lon");
            

            executeScript(AddPushpinScript, "", HomeLon, HomeLat, "", "", "CENTER", "CENTER");

            executeScript(SetCenterAndZoom, HomeLat, HomeLon, Options.GetVEMapZoomLevel());

            Cursor.Current = Cursors.Arrow;
        
        }

        public void mapPositionChange(double lat, double lon, int zoom)
        {
            mapPos.setPosition(lat, lon, zoom);
            //updatePositionLabels();
        }

        private void executeScript(string scriptName, params object[] parameters)
        {
            virtualEarthMapBrowser.Document.InvokeScript(scriptName, parameters);
        }

        private int GetStats(string StatType)
        {
            string ConnString = null;

            switch (StatType.ToUpper())
            {
                case "TOTAL":
                    ConnString = "SELECT COUNT(NAME) FROM tblGeoCache";
                    break;

                case "FOUND":
                    ConnString = "SELECT COUNT(Name) FROM tblGeoCache WHERE Status='Found'";
                    break;

                case "NOTFOUND":
                    ConnString = "SELECT COUNT(Name) FROM tblGeoCache WHERE Status='NotFound'";
                    //MessageBox.Show("NotFound");
                    break;

                case "ARCHIVED":
                    ConnString = "SELECT COUNT(Name) FROM tblGeoCache WHERE Archived='True'";
                    break;


                case "PLACED":
                //Will need to pass the username with this in order to get them    
                //ConnString = "SELECT COUNT(Name) FROM tblGeoCache WHERE Placed='True'";
                    Options Options = new Options();

                    ConnString = "SELECT COUNT(Name) FROM tblGeoCache WHERE PlacedBy LIKE '" + Options.GetOption("PlacedBy").ToString() + "'";
                    break;

            }//End Switch.
            int count = 0;

            SQLiteConnection conn = new SQLiteConnection("data source=" + Application.StartupPath + @"\GeoCaches.db");

            SQLiteCommand cmd = new SQLiteCommand(ConnString, conn);
            //SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM tblGeoCache WHERE Name = 'GCGTW3'", conn);            

            conn.Open();

            try
            {
                count = Convert.ToInt16(cmd.ExecuteScalar());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString() + "\r\n\r\n" + ConnString);
            }
            return (count);
        }


        private void PopulateMap()
        {
            SQLiteConnection conn = new SQLiteConnection("data source=" + Application.StartupPath + @"\GeoCaches.db");

            SQLiteDataReader rdr = null;
            SQLiteCommand cmd = new SQLiteCommand("SELECT Name, Desc, Latitude, Longitude, Status FROM tblGeoCache", conn);

            conn.Open();
            int id = 0;

            string CacheName = null;
            string CacheDesc = null;
            string CacheLat = null;
            string CacheLon = null;
            string CacheIcon = null;

            try
            {
                rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {        
                    //Set the variables a value from the DB.
                    CacheName = rdr["Name"].ToString();
                    CacheDesc = rdr["Desc"].ToString();
                    CacheLat = rdr["Latitude"].ToString();
                    CacheLon = rdr["Longitude"].ToString();
                    
                    //Set the default Icon file.
                    CacheIcon = Application.StartupPath + @"\VE\Traditional.gif";

                    switch (rdr["Status"].ToString().ToLower())
                    {
                        case "found":
                            CacheIcon = Application.StartupPath + @"\VE\FoundIT.gif";
                            //MessageBox.Show("Name: " + CacheName + "\r\nIcon: " + CacheIcon);
                            break;

                    }//END Switch Block
                    executeScript(AddPushpinScript, "", CacheLon, CacheLat, CacheIcon, CacheName, CacheDesc, CacheName);
                    id += 1;
                }//END While Block
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }//END Catch Block
        }

        private void GetData(string Filter)
        //Get the data from the table and populate the DataGridView of caches.
        {
            Options Options = new Options();
            
            string SQL = null;

            if (txtNameSearch.Text == "")
            {
                SQL = "SELECT * FROM tblGeoCache WHERE ";

            }
            else
            {
                SQL = "SELECT * FROM tblGeoCache WHERE Name = '%" + txtNameSearch.Text + "%'";
            }

            //If all of the checkboxes are not checked and there is nothing to be filtered 
            //then we need to remove the WHERE clause from the statement.
            if (txtNameSearch.Text == "" && chkArchived.Checked == false && chkPlaced.Checked == false && chkFound.Checked == false)
                SQL = SQL.Replace(" WHERE ", "");

            //Evaluate checkboxes and build the where clause in the SQL statement.
            if (chkArchived.Checked == true)
            {
                if (txtNameSearch.Text != "")
                    SQL += " AND ";

                SQL += "Archived != 'True' ";
            }

            if (chkPlaced.Checked == true)
            {
                if (chkArchived.Checked == true || txtNameSearch.Text != "")
                    SQL += " AND ";
                
                SQL += "PlacedBy != '" + Options.GetOption("GCUsername") + "' ";
            }

            if (chkFound.Checked == true)
            {
                if (chkPlaced.Checked == true || chkArchived.Checked == true || txtNameSearch.Text != "")
                    SQL += " AND ";

                SQL += "Status != 'Found' ";
            }

            
            try
            {
                String connString = "data source=" + Application.StartupPath + @"\GeoCaches.db";

                SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(SQL, connString);

                SQLiteCommandBuilder cmdBuilder = new SQLiteCommandBuilder(dataAdapter);

                DataTable table = new DataTable();
                table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                dataAdapter.Fill(table);
                bindingSource1.DataSource = table;
                    
                DataGridView.Columns["Name"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Name").Replace("CacheColumn-", ""));
                DataGridView.Columns["Desc"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Desc").Replace("CacheColumn-", ""));
                DataGridView.Columns["URL"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-URL").Replace("CacheColumn-", ""));
                DataGridView.Columns["URLName"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-URLName").Replace("CacheColumn-", ""));
                DataGridView.Columns["Sym"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Sym").Replace("CacheColumn-", ""));
                DataGridView.Columns["PlacedBy"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-PlacedBy").Replace("CacheColumn-", ""));
                DataGridView.Columns["Owner"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Owner").Replace("CacheColumn-", ""));
                DataGridView.Columns["Type"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Type").Replace("CacheColumn-", ""));
                DataGridView.Columns["Container"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Container").Replace("CacheColumn-", ""));
                DataGridView.Columns["Difficulty"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Difficulty").Replace("CacheColumn-", ""));
                DataGridView.Columns["Terrain"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Terrain").Replace("CacheColumn-", ""));
                DataGridView.Columns["Country"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Country").Replace("CacheColumn-", ""));
                DataGridView.Columns["State"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-State").Replace("CacheColumn-", ""));
                DataGridView.Columns["ShortDescription"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Short_Description").Replace("CacheColumn-", ""));
                DataGridView.Columns["LongDescription"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Long_Description").Replace("CacheColumn-", ""));
                DataGridView.Columns["EncodedHints"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Encoded_Hints").Replace("CacheColumn-", ""));
                DataGridView.Columns["Latitude"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Latitude").Replace("CacheColumn-", ""));
                DataGridView.Columns["Longitude"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Longitude").Replace("CacheColumn-", ""));
                DataGridView.Columns["Available"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Available").Replace("CacheColumn-", ""));
                DataGridView.Columns["Archived"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Archived").Replace("CacheColumn-", ""));
                DataGridView.Columns["Status"].Visible = Convert.ToBoolean(Options.GetOption("CacheColumn-Status").Replace("CacheColumn-", ""));
                
                DataGridView.Columns["Name"].ReadOnly = true;
                DataGridView.Columns["Desc"].ReadOnly = true;
                DataGridView.Columns["URL"].ReadOnly = true;
                DataGridView.Columns["URLName"].ReadOnly = true;
                DataGridView.Columns["Sym"].ReadOnly = true;
                DataGridView.Columns["PlacedBy"].ReadOnly = true;
                DataGridView.Columns["Owner"].ReadOnly = true;
                DataGridView.Columns["Type"].ReadOnly = true;
                DataGridView.Columns["Container"].ReadOnly = true;
                DataGridView.Columns["Difficulty"].ReadOnly = true;
                DataGridView.Columns["Terrain"].ReadOnly = true;
                DataGridView.Columns["Country"].ReadOnly = true;
                DataGridView.Columns["State"].ReadOnly = true;
                DataGridView.Columns["ShortDescription"].ReadOnly = true;
                DataGridView.Columns["LongDescription"].ReadOnly = true;
                DataGridView.Columns["EncodedHints"].ReadOnly = true;
                DataGridView.Columns["Latitude"].ReadOnly = true;
                DataGridView.Columns["Longitude"].ReadOnly = true;
                DataGridView.Columns["Available"].ReadOnly = true;
                DataGridView.Columns["Archived"].ReadOnly = true;
                DataGridView.Columns["Status"].ReadOnly = true;
                

            }
            catch (SQLiteException ex)
            {
                MessageBox.Show(ex.ToString() + "\r\n\r\nSQL Statement: " + SQL);
            }

        }

        private void txtNameSearch_TextChanged(object sender, EventArgs e)
        {
            //MessageBox.Show("select * from tblGeoCache WHERE Name LIKE'" + txtNameSearch.Text + "'");
            GetData("Name LIKE '%" + txtNameSearch.Text + "%'");
        }

        private void cmsLogAsFound_Click(object sender, EventArgs e)
        {
            SetCache SetCache = new SetCache();
            SetCache.SetCacheFound(DataGridView.SelectedCells[1].Value.ToString());
        }

        private void chkFound_CheckedChanged(object sender, EventArgs e)
        {
            if (FormLoad == false)
                GetData("Name LIKE '%" + txtNameSearch.Text + "%'");
        }

        private void chkPlaced_CheckedChanged(object sender, EventArgs e)
        {
            if (FormLoad == false)
                GetData("Name LIKE '%" + txtNameSearch.Text + "%'");

        }

        private void chkArchived_CheckedChanged(object sender, EventArgs e)
        {
            if (FormLoad == false)
                GetData("Name LIKE '%" + txtNameSearch.Text + "%'");

        }




        private void cmdSendToGPSr_Click(object sender, EventArgs e)
        {
            //string[] arrSelectedCaches;
            //arrSelectedCaches = new string[300];

            ArrayList arrSelectedCaches = new ArrayList();

            foreach (DataGridViewRow row in DataGridView.Rows)
            {
                if (Convert.ToBoolean(row.Cells[0].Value) == true)
                {
                    arrSelectedCaches.Add(row.Cells[1].Value.ToString());
                }//END IF
            }//END FOREACH

            frmSendToGPS SendToGPS = new frmSendToGPS();
            SendToGPS.arrCaches = arrSelectedCaches;
            SendToGPS.ShowDialog();

        }
    }
}